#$language = "Python"
#$interface = "1.0"

import os
import sys
import time

g_local_path = os.path.dirname(os.path.abspath(__file__))
g_common_path = g_local_path + "\\common"
if g_common_path not in sys.path:
    sys.path.insert(0, g_common_path)

import sftp
import debug
import screen
from const import *

TESTER_LOG_PATH = 'D:\\_logs\\Tester_log'

class GetTesterLog():
    su_guest = False
    def __init__(self, obj):
        self.obj = obj
        self.crt = None
        self.log = debug.Log('tester: ')
        if self._check_session_style() and self._check_ets():
            self._get_tester_log()

    def __del__(self):
        del self.log
        if self.crt is not None:
            del self.crt
        if self.su_guest:
            self.obj.Screen.Send('exit\r')

    def _check_session_style(self):
        self.prompt = screen.Prompt()
        self.prompt.set_prompt(crt)
        if self.prompt.style != CONST_STYLE_LINUX:
            self.log.w('This session {0} not support.'.format(prompt.style))
            rslt = False
        else:
            if self.prompt.char == CONST_PROMPT_LINUX_ROOT:
                self.obj.Screen.Send('su guest\r')
                self.obj.Screen.WaitForString(CONST_JUST_WAIT, 1)
                self.su_guest = True
                self.prompt.set_prompt(crt)
            self.crt = screen.Screen(self.obj, self.prompt)
            rslt = True
        del self.prompt
        return rslt
        
    def _check_ets(self):
        rspd = self.crt.send('pwd\r')
        if 'ets' in rspd:
            paths = rspd.split('/')
            paths.reverse()
            for var in paths:
                if var != 'ets':
                    self.crt.send('cd ..\r')
                else:
                    break
            rslt = True
        else:
            rspd = self.crt.send('ls\r')
            if 'ets' in rspd:
                rspd = self.crt.send('cd ets\r')
                if not rspd:
                    rslt = True
                else:
                    rslt = False
            elif 'test.sh' in rspd:
                rslt = True
            else:
                rslt = False
        if not rslt:
            self.log.w('ets check failure.')
        self.ets = self.crt.send('pwd\r')
        return rslt

    def _check_log_read(self):
        rspd = self.crt.send('ls -l log.txt\r')
        splits = rspd.split()
        if splits[2] == 'guest':
            if splits[0][1] != 'r' and splits[0][4] != 'r':
                self.crt.send('chmod a+r *.txt\r')
            return True
        else:
            return splits[0][7] == 'r'

    def _get_tester_log(self):
        rspd = self.crt.send('cd log\r')
        if rspd:
            self.log.w('log folder not exist.')
            return False

        if not self._check_log_read():
            self.log.w('no rights to read log files, login as root')
            # change root user
            self.obj.Screen.Send('su\r')
            if self.obj.Screen.WaitForString('Password: ', 2):
                self.obj.Screen.Send('ruutti\r')
                self.obj.Screen.WaitForString(CONST_JUST_WAIT, 1)

            prompt = screen.Prompt(CONST_PROMPT_LINUX_ROOT)
            self.crt.send('chmod a+r *.txt\r', prompt = prompt)
            del prompt
            self.crt.send('exit\r')
        
        peu_log = '/data/PeuLOG/log'
        peu_lock = '/data/PeuLOG/lock'
        peu_log_new_name = 'peu_log.txt'
        
        cmd = 'test -e {0} && (kill -10 $(cat {0}); rm -f {0})\r'.format(
            peu_lock)
        self.crt.send(cmd)
        self.crt.send('cp {0} {1}\r'.format(peu_log, peu_log_new_name))

        zip_log_file = 'tester.zip'
        self.crt.send('test -e {0} && rm -f {0}\r'.format(zip_log_file))
        self.crt.send('zip {0} *.txt\r'.format(zip_log_file))
        self.crt.send('rm {0}\r'.format(peu_log_new_name))

        log_head = crt.Dialog.Prompt("Enter log name:", "Name")
        if not log_head:
            log_head = (self.obj.Session.Path).split('\\').pop()

        log_folder = TESTER_LOG_PATH + '\\' + \
            log_head + time.strftime('_%Y%m%d_%H%M', time.localtime())
        if not os.path.exists(log_folder): 
            os.makedirs(log_folder)
            self.log.w('mkdir ' + log_folder)

        ftp = sftp.Sftp(self.obj)
        if ftp.cd(self.ets + '/log') and ftp.lcd(log_folder):
            rslt = ftp.get(zip_log_file)
            if self.crt.send('ls -t *.pcap 2>/dev/null | sed -n "1p"\r'):
                rslt = rslt and ftp.get(self.crt.get_respond())
                self.crt.send('mkdir -p wireshark\r')
                self.crt.send('mv *.pcap wireshark/\r')
            if ftp.cd(self.ets + '/config'):
                rslt = rslt and ftp.get('parameters.conf')
            else:
                rslt = False
        else:
            rslt = False
        del ftp
        self.crt.send('cd ..\r')
        return rslt

def main():
    crt.Screen.Synchronous = True

    session_name = (crt.Session.Path).split('\\').pop()
    if 'Tester' not in session_name:
        debug.pop_error('This session is not a tester.', crt)
        crt.Screen.Synchronous = False
        return None

    debug.log_start(__file__)
    get_log = GetTesterLog(crt)
    del get_log
    crt.Screen.Synchronous = False
    return None

main()
